package com.sunwayworld.basemodule.business.sampleprocess.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sunwayworld.basemodule.business.batch.bean.LimsBatchSampleBean;
import com.sunwayworld.basemodule.business.batch.bean.LimsBatchSampleProductBean;
import com.sunwayworld.basemodule.business.batch.service.LimsBatchSampleProductService;
import com.sunwayworld.basemodule.business.batch.service.LimsBatchSampleService;
import com.sunwayworld.basemodule.business.folder.bean.LimsFolderBean;
import com.sunwayworld.basemodule.business.folder.bean.LimsPreOrderTaskBean;
import com.sunwayworld.basemodule.business.folder.service.LimsFolderService;
import com.sunwayworld.basemodule.business.folder.service.LimsPreOrderTaskService;
import com.sunwayworld.basemodule.business.sampleprocess.dto.LimsSampleProcessDataDto;
import com.sunwayworld.basemodule.business.sampleprocess.dto.LimsSampleProcessDataSearchDto;
import com.sunwayworld.basemodule.business.sampleprocess.dto.LimsSampleProcessStepDto;
import com.sunwayworld.basemodule.business.sampleprocess.dto.LimsSampleProcessTaskDto;
import com.sunwayworld.basemodule.business.sampleprocess.service.LimsSampleProcessService;
import com.sunwayworld.basemodule.coredata.experimentaltemplate.bean.LimsExperimentalTemplateTestBean;
import com.sunwayworld.basemodule.coredata.experimentaltemplate.service.LimsExperimentalTemplateTestService;
import com.sunwayworld.basemodule.samplemanage.sample.bean.LimsSampleBean;
import com.sunwayworld.basemodule.samplemanage.sample.service.LimsSampleService;
import com.sunwayworld.framework.database.sql.Order;
import com.sunwayworld.framework.mybatis.mapper.MapperParameter;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName LimsSampleProcessServiceImpl
 * @Author zhoujq
 * @Date 2023/4/4
 * @Version 1.0
 **/
@Service
@GikamBean
public class LimsSampleProcessServiceImpl implements LimsSampleProcessService {

    @Autowired
    @Lazy
    private LimsBatchSampleProductService limsBatchSampleProductService;

    @Autowired
    @Lazy
    private LimsSampleService limsSampleService;

    @Autowired
    @Lazy
    private LimsFolderService limsFolderService;

    @Lazy
    @Autowired
    private LimsExperimentalTemplateTestService etTestService;

    @Lazy
    @Autowired
    private LimsPreOrderTaskService limsPreOrderTaskService;

    @Lazy
    @Autowired
    private LimsBatchSampleService limsBatchSampleService;

    @Override
    public List<LimsBatchSampleProductBean> selectSampleProductList(LimsSampleProcessDataSearchDto searchDto) {
        MapperParameter parameter = new MapperParameter();
        return limsBatchSampleProductService.selectList(parameter);
    }

/*    @Override
    public JSONObject processSearch(LimsSampleProcessDataSearchDto searchDto) {
        JSONObject req = new JSONObject();
        LimsSampleBean sampleBean = null;
        if (searchDto.getSampleId() != null) {
            sampleBean = limsSampleService.selectByIdIfPresent(searchDto.getSampleId());
        } else {
            req.put("data", Collections.emptyList());
            return req;
        }
        if (sampleBean != null && sampleBean.getId() != null) {
            List<LimsBatchSampleProductBean> productBeans = limsBatchSampleProductService.selectListByFilter(SearchFilter.instance().match("sampleid", sampleBean.getId()).filter(MatchPattern.EQ), Order.asc("sampleCode"), Order.asc("productCode"));
            if (productBeans.isEmpty()) {
                req.put("data", Collections.emptyList());
                return req;
            }
            List<Long> batchSampleIds = productBeans.stream().map(LimsBatchSampleProductBean::getBatchSampleId).distinct().collect(Collectors.toList());
            List<Long> productIds = productBeans.stream().map(LimsBatchSampleProductBean::getProductId).distinct().collect(Collectors.toList());
            List<LimsFolderBean> folderBeans = limsFolderService.selectListByFilter(SearchFilter.instance().match("batchSampleId", batchSampleIds).filter(MatchPattern.OR).match("productId", productIds).filter(MatchPattern.OR));
            List<LimsPreOrderTaskBean> preOrderTaskBeans = limsPreOrderTaskService.selectBySamplePreTasks(SearchFilter.instance().match("batchSampleId", batchSampleIds).filter(MatchPattern.OR));

            // 拼数据
            List<LimsSampleProcessDataDto> data = new ArrayList<>();
            productBeans.forEach(p -> {
                LimsSampleProcessDataDto row = new LimsSampleProcessDataDto();
                row.setBatchCode(p.getBatchCode());
                row.setBatchId(p.getBatchId());
                row.setSampleId(p.getSampleId());
                row.setSampleCode(p.getSampleCode());
                row.setBatchSampleId(p.getBatchSampleId());
                row.setProductId(p.getProductId());
                row.setProductCode(p.getProductCode());
                row.setProductName(p.getProductName());
                row.setStatus(p.getStatus());

                // 拼节点数据
                List<LimsSampleProcessTaskDto> taskDtos = new ArrayList<>();

                // 样本接收
                LimsSampleProcessTaskDto firstStep = new LimsSampleProcessTaskDto();
                firstStep.setTaskName("样本接收");
                firstStep.setStatus(p.getStatus());
                if (p.getStatus().equals("receive") || p.getStatus().equals("draft")) {
                    firstStep.setStatusName("待接收");
                    firstStep.setColor("3");
                    taskDtos.add(firstStep);

                    row.setList(taskDtos);
                    data.add(row);
                } else if (p.getStatus().equals("abnormal")) {
                    firstStep.setTaskName("样本异常");
                    firstStep.setStatusName("样本异常");
                    firstStep.setColor("4");
                    taskDtos.add(firstStep);

                    row.setList(taskDtos);
                    data.add(row);
                } else if (p.getStatus().equals("stop")) {
                    firstStep.setTaskName("样本终止");
                    firstStep.setStatusName("样本终止");
                    firstStep.setColor("4");
                    taskDtos.add(firstStep);

                    row.setList(taskDtos);
                    data.add(row);
                } else {
                    firstStep.setStatusName("已接收");
                    firstStep.setColor("1");
                    taskDtos.add(firstStep);

                    // 样本接收已完成的，查找下发的批次
                    folderBeans.stream().filter(f -> f.getProductId().equals(p.getProductId()) && f.getBatchSampleId().equals(p.getBatchSampleId())).sorted(Comparator.comparing(LimsFolderBean::getId)).forEach(f -> {
                        List<LimsPreOrderTaskBean> temp = preOrderTaskBeans.stream().filter(po -> po.getFolderId().equals(f.getId())).sorted(Comparator.comparing(LimsPreOrderTaskBean::getSort)).collect(Collectors.toList());
                        if (!temp.isEmpty()) {
                            for (int i = 0; i < temp.size(); i++) {
                                LimsPreOrderTaskBean ot = temp.get(i);
                                LimsSampleProcessTaskDto taskDto = new LimsSampleProcessTaskDto();
                                taskDto.setTaskName(ot.getTestName());
                                taskDto.setStatus(ot.getStatus());
                                if (ot.getStatus().equals("draft")) {
                                    taskDto.setColor("3");
                                    taskDto.setStatusName("待下发");
                                    taskDtos.add(taskDto);
                                } else if (ot.getStatus().equals("done")) {
                                    taskDto.setColor("1");
                                    taskDto.setStatusName("已完成");
                                    taskDtos.add(taskDto);
                                } else if (ot.getStatus().equals("logged")) {
                                    taskDto.setColor("2");
                                    taskDto.setStatusName("已下发");
                                    taskDtos.add(taskDto);
                                } else if (ot.getStatus().equals("stop")) {
                                    taskDto.setColor("4");
                                    taskDto.setStatusName("实验终止");
                                    taskDtos.add(taskDto);

                                    if (i < temp.size()) {
                                        for (int j = i + 1; j < temp.size(); j++) {
                                            LimsPreOrderTaskBean ot2 = temp.get(i);
                                            LimsSampleProcessTaskDto afterStops = new LimsSampleProcessTaskDto();
                                            afterStops.setTaskName(ot2.getTestName());
                                            afterStops.setStatus("stop");
                                            afterStops.setColor("4");
                                            afterStops.setStatusName("实验终止");

                                            taskDtos.add(afterStops);
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    });

                    row.setList(taskDtos);
                    data.add(row);
                }
            });
            req.put("data", data);
            return req;
        }
        req.put("data", Collections.emptyList());
        return req;
    }*/

    @Override
    public List<LimsSampleBean> selectSampleList(JSONObject rep) {
        MapperParameter parameter = new MapperParameter();
        if (!rep.isEmpty()) {
            SearchFilter filter = SearchFilter.instance();
            rep.forEach((k, v) -> {
                if (v != null) {
                    filter.match(k, v).filter(MatchPattern.SC);
                }
            });
            parameter.setFilter(filter);
        }
        return limsSampleService.selectListByParams(parameter);
    }

    @Override
    public JSONObject processSearch3(LimsSampleProcessDataSearchDto searchDto) {
        JSONObject req = new JSONObject();

        List<LimsSampleProcessDataDto> listData = new ArrayList<>();
        req.put("listData", listData);

        if (searchDto.getSampleId() == null) {
            req.put("listData", Collections.emptyList());
            return req;
        }

//        LimsSampleBean sampleBean = limsSampleService.selectByIdIfPresent(searchDto.getSampleId());
        LimsBatchSampleBean batchSampleBean = limsBatchSampleService.selectFirstByFilter(SearchFilter.instance().match("id", searchDto.getSampleId()).filter(MatchPattern.EQ));
        if (batchSampleBean == null) {
            return req;
        }
        List<LimsBatchSampleProductBean> productBeans = limsBatchSampleProductService.selectListByFilter(SearchFilter.instance().match("batchSampleId", batchSampleBean.getId()).filter(MatchPattern.EQ), Order.asc("productCode"));
        if (productBeans.isEmpty()) {
            req.put("data", Collections.emptyList());
            return req;
        }
        List<Long> batchSampleIds = productBeans.stream().map(LimsBatchSampleProductBean::getBatchSampleId).distinct().collect(Collectors.toList());
        List<Long> productIds = productBeans.stream().map(LimsBatchSampleProductBean::getProductId).distinct().collect(Collectors.toList());
        List<LimsFolderBean> folderBeans = limsFolderService.selectListByFilter(SearchFilter.instance().match("batchSampleId", batchSampleIds).filter(MatchPattern.OR).match("productId", productIds).filter(MatchPattern.OR));
        List<LimsPreOrderTaskBean> preOrderTaskBeans = limsPreOrderTaskService.selectBySamplePreTasks(SearchFilter.instance().match("batchSampleId", batchSampleIds).filter(MatchPattern.OR));
        List<Long> etTestIds = preOrderTaskBeans.stream().map(LimsPreOrderTaskBean::getEtTestId).distinct().collect(Collectors.toList());
        List<LimsExperimentalTemplateTestBean> etTests = etTestService.selectListByIds(etTestIds);
        preOrderTaskBeans.forEach(po -> {
            etTests.stream().filter(et -> et.getId().equals(po.getEtTestId())).findAny().ifPresent(et -> {
                if (StringUtils.isBlank(po.getLastEtTestIds())) {
                    po.setLastEtTestIds(et.getLastTestIds());
                }
            });
        });
        productBeans.forEach(p -> {
            LimsSampleProcessDataDto row = new LimsSampleProcessDataDto();
            row.setTitle(p.getProductName());
            listData.add(row);

            // 拼节点数据
            List<LimsSampleProcessTaskDto> taskDtos = new ArrayList<>();
            row.setList(taskDtos);

            LimsSampleProcessTaskDto startTask = new LimsSampleProcessTaskDto();
            taskDtos.add(startTask);
            startTask.setStep(1);
            startTask.setStart(true);

            LimsSampleProcessStepDto startStep = new LimsSampleProcessStepDto();
            startStep.setStart(true);
            startStep.setStatus(3);
            startTask.setList(Collections.singletonList(startStep));

            // 样本接收
            LimsSampleProcessTaskDto receiveTask = new LimsSampleProcessTaskDto();
            receiveTask.setStep(2);
            taskDtos.add(receiveTask);
            if (p.getStatus().equals("receive") || p.getStatus().equals("draft")) {
                LimsSampleProcessStepDto receiveStep = new LimsSampleProcessStepDto();
                receiveStep.setTxt("待接收");
                receiveStep.setStatus(1);
                receiveTask.setList(Collections.singletonList(receiveStep));
            } else if (p.getStatus().equals("abnormal")) {
                LimsSampleProcessStepDto receiveStep = new LimsSampleProcessStepDto();
                receiveStep.setTxt("样本异常");
                receiveStep.setStatus(4);
                receiveTask.setList(Collections.singletonList(receiveStep));
            } else if (p.getStatus().equals("stop")) {
                LimsSampleProcessStepDto receiveStep = new LimsSampleProcessStepDto();
                receiveStep.setTxt("样本终止");
                receiveStep.setStatus(4);
                receiveTask.setList(Collections.singletonList(receiveStep));
            } else {
                LimsSampleProcessStepDto receiveStep = new LimsSampleProcessStepDto();
                receiveStep.setTxt("已接收");
                receiveStep.setStatus(3);
                receiveTask.setList(Collections.singletonList(receiveStep));

                int fromNum = 3;
                // 样本接收已完成的，查找下发的批次
                folderBeans.stream().filter(f -> f.getProductId().equals(p.getProductId()) && f.getBatchSampleId().equals(p.getBatchSampleId())).sorted(Comparator.comparing(LimsFolderBean::getId)).forEach(f -> {
                    List<LimsPreOrderTaskBean> temp = preOrderTaskBeans.stream().filter(po -> po.getFolderId().equals(f.getId())).sorted(Comparator.comparing(LimsPreOrderTaskBean::getSort)).collect(Collectors.toList());
                    if (!temp.isEmpty()) {
                        Map<Long, List<LimsPreOrderTaskBean>> groupBySort = temp.stream().collect(Collectors.groupingBy(LimsPreOrderTaskBean::getSort));
                        groupBySort.keySet().stream().sorted(Long::compareTo).forEach(sort -> {
                            List<LimsPreOrderTaskBean> temp2 = groupBySort.get(sort);
                            LimsSampleProcessTaskDto lastTask = taskDtos.get(taskDtos.size() - 1);
                            // 如果排序码相同的不止一个
                            if (temp2.size() > 1) {
                                if (lastTask.getList().size() == 1) {
                                    // 如果上一个节点只有一个工序，则是从上一个节点开始分支
//                                    lastTask.setLeft(true);

                                    List<LimsSampleProcessStepDto> list = new ArrayList<>();
                                    LimsSampleProcessTaskDto taskDto = new LimsSampleProcessTaskDto();
                                    taskDto.setLeft(true);
                                    if (lastTask.getList().get(0).getStatus() == 2) {
                                        taskDto.setLeftStatus(1);
                                    } else {
                                        taskDto.setLeftStatus(lastTask.getList().get(0).getStatus());
                                    }
                                    taskDto.setStep(taskDtos.size() + 1);
                                    taskDtos.add(taskDto);
                                    temp2.forEach(ot -> {
                                        LimsSampleProcessStepDto taskStep = new LimsSampleProcessStepDto();
                                        taskStep.setTxt(ot.getTestName());
                                        taskStep.setEtTestId(ot.getEtTestId());
                                        if (ot.getStatus().equals("draft")) {
                                            taskStep.setStatus(1);
                                        } else if (ot.getStatus().equals("done")) {
                                            taskStep.setStatus(3);
                                        } else if (ot.getStatus().equals("logged")) {
                                            taskStep.setStatus(2);
                                        } else if (ot.getStatus().equals("stop")) {
                                            taskStep.setStatus(4);
                                        }
                                        list.add(taskStep);
                                    });
                                    taskDto.setList(list);
                                } else {
                                    // 如果上一个节点也有多个工序，则按LimsPreOrderTaskBean里的上一工序id来匹配
                                    List<LimsSampleProcessStepDto> list = new ArrayList<>();
                                    LimsSampleProcessTaskDto taskDto = new LimsSampleProcessTaskDto();
                                    taskDto.setStep(taskDtos.size() + 1);
//                                    taskDto.setLeft(true);
                                    taskDtos.add(taskDto);
                                    for (int i = 0; i < lastTask.getList().size(); i++) {
                                        LimsSampleProcessStepDto lastStep = lastTask.getList().get(i);
                                        Optional<LimsPreOrderTaskBean> optional = temp2.stream().filter(ot -> ot.getLastEtTestIds().contains(lastStep.getEtTestId().toString())).findAny();
                                        if (optional.isPresent()) {
                                            LimsSampleProcessStepDto taskStep = new LimsSampleProcessStepDto();
                                            taskStep.setTxt(optional.get().getTestName());
                                            taskStep.setEtTestId(optional.get().getEtTestId());
                                            if (optional.get().getStatus().equals("draft")) {
                                                taskStep.setStatus(1);
                                            } else if (optional.get().getStatus().equals("done")) {
                                                taskStep.setStatus(3);
                                            } else if (optional.get().getStatus().equals("logged")) {
                                                taskStep.setStatus(2);
                                            } else if (optional.get().getStatus().equals("stop")) {
                                                taskStep.setStatus(4);
                                            }
                                            list.add(taskStep);
                                        } else {
/*                                            LimsSampleProcessStepDto taskStep = new LimsSampleProcessStepDto();
                                            taskStep.setTxt("");
                                            taskStep.setEtTestId(optional.get().getEtTestId());*/
                                        }
                                    }
                                    taskDto.setList(list);
                                }
                            } else {// 排序码相同的只有一个
                                LimsPreOrderTaskBean ot = temp2.get(0);

                                LimsSampleProcessTaskDto taskDto = new LimsSampleProcessTaskDto();
                                taskDto.setStep(taskDtos.size() + 1);
                                taskDtos.add(taskDto);
                                LimsSampleProcessStepDto taskStep = new LimsSampleProcessStepDto();
                                taskDto.setList(Collections.singletonList(taskStep));
                                taskStep.setTxt(ot.getTestName());
                                taskStep.setEtTestId(ot.getEtTestId());
                                if (ot.getStatus().equals("draft")) {
                                    taskStep.setStatus(1);
                                } else if (ot.getStatus().equals("done")) {
                                    taskStep.setStatus(3);
                                } else if (ot.getStatus().equals("logged")) {
                                    taskStep.setStatus(2);
                                } else if (ot.getStatus().equals("stop")) {
                                    taskStep.setStatus(4);
                                }

                                if (lastTask.getList().size() == 1) {
                                } else {
                                    lastTask.setRight(true);
                                    if (lastTask.getList().stream().allMatch(t -> t.getStatus() == 3)) {
                                        lastTask.setRightStatus(3);
                                    } else if (lastTask.getList().stream().allMatch(t -> t.getStatus() == 4)) {
                                        lastTask.setRightStatus(4);
                                    } else {
                                        lastTask.setRightStatus(1);
                                    }
                                }
                            }
                        });
                    }
                });
            }
            // 结束节点
            LimsSampleProcessTaskDto endTask = new LimsSampleProcessTaskDto();
            endTask.setStep(taskDtos.size() + 1);
            endTask.setEnd(true);
            List<LimsSampleProcessStepDto> lastList = taskDtos.get(taskDtos.size() - 1).getList();
            taskDtos.add(endTask);

            List<LimsSampleProcessStepDto> list = new ArrayList<>();
            endTask.setList(list);
            for (int i = 0; i < lastList.size(); i++) {
                LimsSampleProcessStepDto endStep = new LimsSampleProcessStepDto();
                endStep.setEnd(true);
                list.add(endStep);
                if (lastList.get(i).getStatus() == 2) {
                    endStep.setStatus(1);
                } else {
                    endStep.setStatus(lastList.get(i).getStatus());
                }
            }
        });
        return req;
    }

    @Override
    public JSONObject processSearch4(LimsSampleProcessDataSearchDto searchDto) {
        JSONObject req = new JSONObject();

        List<LimsSampleProcessDataDto> listData = new ArrayList<>();
        req.put("listData", listData);

        if (searchDto.getSampleId() == null) {
            req.put("listData", Collections.emptyList());
            return req;
        }

        LimsBatchSampleProductBean productBean = limsBatchSampleProductService.selectFirstByFilter(SearchFilter.instance().match("id", searchDto.getSampleId()).filter(MatchPattern.EQ));
        if (productBean == null) {
            return req;
        }
        List<LimsBatchSampleProductBean> productBeans = Collections.singletonList(productBean);
        List<Long> batchSampleIds = productBeans.stream().map(LimsBatchSampleProductBean::getBatchSampleId).distinct().collect(Collectors.toList());
        List<String> productCodes = productBeans.stream().map(LimsBatchSampleProductBean::getProductCode).distinct().collect(Collectors.toList());
        List<LimsFolderBean> folderBeans = limsFolderService.selectListByFilter(SearchFilter.instance().match("batchSampleId", batchSampleIds).filter(MatchPattern.OR).match("productCode", productCodes).filter(MatchPattern.OR));
        List<LimsPreOrderTaskBean> preOrderTaskBeans = limsPreOrderTaskService.selectBySamplePreTasks(SearchFilter.instance().match("batchSampleId", batchSampleIds).filter(MatchPattern.OR));
        List<Long> etTestIds = preOrderTaskBeans.stream().map(LimsPreOrderTaskBean::getEtTestId).distinct().collect(Collectors.toList());
        List<LimsExperimentalTemplateTestBean> etTests = etTestService.selectListByIds(etTestIds);
        preOrderTaskBeans.forEach(po -> {
            etTests.stream().filter(et -> et.getId().equals(po.getEtTestId())).findAny().ifPresent(et -> {
                if (StringUtils.isBlank(po.getLastEtTestIds())) {
                    po.setLastEtTestIds(et.getLastTestIds());
                }
            });
        });
        List<String> notStartStatus = Arrays.asList("draft", "receive", "abnormal", "abnormalConfirm", "stop");
        productBeans.forEach(p -> {
            if (notStartStatus.stream().anyMatch(ns -> ns.equals(p.getStatus()))) {
                LimsSampleProcessDataDto row = new LimsSampleProcessDataDto();
                row.setTitle(p.getProductName());
                listData.add(row);

                // 拼节点数据
                List<LimsSampleProcessTaskDto> taskDtos = new ArrayList<>();
                row.setList(taskDtos);

                LimsSampleProcessTaskDto startTask = new LimsSampleProcessTaskDto();
                taskDtos.add(startTask);
                startTask.setStep(1);
                startTask.setStart(true);

                LimsSampleProcessStepDto startStep = new LimsSampleProcessStepDto();
                startStep.setStart(true);
                startStep.setStatus(3);
                startTask.setList(Collections.singletonList(startStep));

                // 样本接收
                LimsSampleProcessTaskDto receiveTask = new LimsSampleProcessTaskDto();
                receiveTask.setStep(2);
                taskDtos.add(receiveTask);
                if (p.getStatus().equals("receive") || p.getStatus().equals("draft")) {
                    LimsSampleProcessStepDto receiveStep = new LimsSampleProcessStepDto();
                    receiveStep.setTxt("待接收");
                    receiveStep.setStatus(1);
                    receiveTask.setList(Collections.singletonList(receiveStep));
                } else if (p.getStatus().equals("abnormal")) {
                    LimsSampleProcessStepDto receiveStep = new LimsSampleProcessStepDto();
                    receiveStep.setTxt("样本异常");
                    receiveStep.setStatus(4);
                    receiveTask.setList(Collections.singletonList(receiveStep));
                } else if (p.getStatus().equals("abnormalConfirm")) {
                    LimsSampleProcessStepDto receiveStep = new LimsSampleProcessStepDto();
                    receiveStep.setTxt("样本异常处理执行");
                    receiveStep.setStatus(4);
                    receiveTask.setList(Collections.singletonList(receiveStep));
                } else if (p.getStatus().equals("stop")) {
                    LimsSampleProcessStepDto receiveStep = new LimsSampleProcessStepDto();
                    receiveStep.setTxt("样本终止");
                    receiveStep.setStatus(4);
                    receiveTask.setList(Collections.singletonList(receiveStep));
                }
                // 结束节点
                LimsSampleProcessTaskDto endTask = new LimsSampleProcessTaskDto();
                endTask.setStep(taskDtos.size() + 1);
                endTask.setEnd(true);
                List<LimsSampleProcessStepDto> lastList = taskDtos.get(taskDtos.size() - 1).getList();
                taskDtos.add(endTask);

                List<LimsSampleProcessStepDto> list = new ArrayList<>();
                endTask.setList(list);
                for (int i = 0; i < lastList.size(); i++) {
                    LimsSampleProcessStepDto endStep = new LimsSampleProcessStepDto();
                    endStep.setEnd(true);
                    list.add(endStep);
                    if (lastList.get(i).getStatus() == 2) {
                        endStep.setStatus(1);
                    } else {
                        endStep.setStatus(lastList.get(i).getStatus());
                    }
                }
            } else {
                // 样本接收已完成的，查找下发的批次
                folderBeans.stream().filter(f -> f.getProductCode().equals(p.getProductCode()) && f.getBatchSampleId().equals(p.getBatchSampleId())).sorted(Comparator.comparing(LimsFolderBean::getId)).forEach(f -> {
                    // 一个任务单一条数据
                    LimsSampleProcessDataDto row = new LimsSampleProcessDataDto();
                    row.setTitle(f.getProductName());
                    listData.add(row);

                    // 拼节点数据
                    List<LimsSampleProcessTaskDto> taskDtos = new ArrayList<>();
                    row.setList(taskDtos);

                    LimsSampleProcessTaskDto startTask = new LimsSampleProcessTaskDto();
                    taskDtos.add(startTask);
                    startTask.setStep(1);
                    startTask.setStart(true);

                    LimsSampleProcessStepDto startStep = new LimsSampleProcessStepDto();
                    startStep.setStart(true);
                    startStep.setStatus(3);
                    startTask.setList(Collections.singletonList(startStep));

                    // 样本接收
                    LimsSampleProcessTaskDto receiveTask = new LimsSampleProcessTaskDto();
                    receiveTask.setStep(2);
                    taskDtos.add(receiveTask);

                    LimsSampleProcessStepDto receiveStep = new LimsSampleProcessStepDto();
                    receiveStep.setTxt("已接收");
                    receiveStep.setStatus(3);
                    receiveTask.setList(Collections.singletonList(receiveStep));

                    List<LimsPreOrderTaskBean> temp = preOrderTaskBeans.stream().filter(po -> po.getFolderId().equals(f.getId())).sorted(Comparator.comparing(LimsPreOrderTaskBean::getSort)).collect(Collectors.toList());
                    if (!temp.isEmpty()) {
                        Map<Long, List<LimsPreOrderTaskBean>> groupBySort = temp.stream().collect(Collectors.groupingBy(LimsPreOrderTaskBean::getSort));
                        groupBySort.keySet().stream().sorted(Long::compareTo).forEach(sort -> {
                            List<LimsPreOrderTaskBean> temp2 = groupBySort.get(sort);
                            LimsSampleProcessTaskDto lastTask = taskDtos.get(taskDtos.size() - 1);
                            // 如果排序码相同的不止一个
                            if (temp2.size() > 1) {
                                if (lastTask.getList().size() == 1) {
                                    // 如果上一个节点只有一个工序，则是从上一个节点开始分支
//                                    lastTask.setLeft(true);

                                    List<LimsSampleProcessStepDto> list = new ArrayList<>();
                                    LimsSampleProcessTaskDto taskDto = new LimsSampleProcessTaskDto();
                                    taskDto.setLeft(true);
                                    if (lastTask.getList().get(0).getStatus() == 2) {
                                        taskDto.setLeftStatus(1);
                                    } else {
                                        taskDto.setLeftStatus(lastTask.getList().get(0).getStatus());
                                    }
                                    taskDto.setStep(taskDtos.size() + 1);
                                    taskDtos.add(taskDto);
                                    temp2.forEach(ot -> {
                                        LimsSampleProcessStepDto taskStep = new LimsSampleProcessStepDto();
                                        taskStep.setTxt(ot.getTestName());
                                        taskStep.setEtTestId(ot.getEtTestId());
                                        if (ot.getStatus().equals("draft")) {
                                            taskStep.setStatus(1);
                                        } else if (ot.getStatus().equals("done")) {
                                            taskStep.setStatus(3);
                                        } else if (ot.getStatus().equals("logged")) {
                                            taskStep.setStatus(2);
                                        } else if (ot.getStatus().equals("stop")) {
                                            taskStep.setStatus(4);
                                        }
                                        list.add(taskStep);
                                    });
                                    taskDto.setList(list);
                                } else {
                                    // 如果上一个节点也有多个工序，则按LimsPreOrderTaskBean里的上一工序id来匹配
                                    List<LimsSampleProcessStepDto> list = new ArrayList<>();
                                    LimsSampleProcessTaskDto taskDto = new LimsSampleProcessTaskDto();
                                    taskDto.setStep(taskDtos.size() + 1);
//                                    taskDto.setLeft(true);
                                    taskDtos.add(taskDto);
                                    for (int i = 0; i < lastTask.getList().size(); i++) {
                                        LimsSampleProcessStepDto lastStep = lastTask.getList().get(i);
                                        Optional<LimsPreOrderTaskBean> optional = temp2.stream().filter(ot -> ot.getLastEtTestIds().contains(lastStep.getEtTestId().toString())).findAny();
                                        if (optional.isPresent()) {
                                            LimsSampleProcessStepDto taskStep = new LimsSampleProcessStepDto();
                                            taskStep.setTxt(optional.get().getTestName());
                                            taskStep.setEtTestId(optional.get().getEtTestId());
                                            if (optional.get().getStatus().equals("draft")) {
                                                taskStep.setStatus(1);
                                            } else if (optional.get().getStatus().equals("done")) {
                                                taskStep.setStatus(3);
                                            } else if (optional.get().getStatus().equals("logged")) {
                                                taskStep.setStatus(2);
                                            } else if (optional.get().getStatus().equals("stop")) {
                                                taskStep.setStatus(4);
                                            }
                                            list.add(taskStep);
                                        } else {
/*                                            LimsSampleProcessStepDto taskStep = new LimsSampleProcessStepDto();
                                            taskStep.setTxt("");
                                            taskStep.setEtTestId(optional.get().getEtTestId());*/
                                        }
                                    }
                                    taskDto.setList(list);
                                }
                            } else {// 排序码相同的只有一个
                                LimsPreOrderTaskBean ot = temp2.get(0);

                                LimsSampleProcessTaskDto taskDto = new LimsSampleProcessTaskDto();
                                taskDto.setStep(taskDtos.size() + 1);
                                taskDtos.add(taskDto);
                                LimsSampleProcessStepDto taskStep = new LimsSampleProcessStepDto();
                                taskDto.setList(Collections.singletonList(taskStep));
                                taskStep.setTxt(ot.getTestName());
                                taskStep.setEtTestId(ot.getEtTestId());
                                if (ot.getStatus().equals("draft")) {
                                    taskStep.setStatus(1);
                                } else if (ot.getStatus().equals("done")) {
                                    taskStep.setStatus(3);
                                } else if (ot.getStatus().equals("logged")) {
                                    taskStep.setStatus(2);
                                } else if (ot.getStatus().equals("stop")) {
                                    taskStep.setStatus(4);
                                }

                                if (lastTask.getList().size() == 1) {
                                } else {
                                    lastTask.setRight(true);
                                    if (lastTask.getList().stream().allMatch(t -> t.getStatus() == 3)) {
                                        lastTask.setRightStatus(3);
                                    } else if (lastTask.getList().stream().allMatch(t -> t.getStatus() == 4)) {
                                        lastTask.setRightStatus(4);
                                    } else {
                                        lastTask.setRightStatus(1);
                                    }
                                }
                            }
                        });
                    }
                    // 结束节点
                    LimsSampleProcessTaskDto endTask = new LimsSampleProcessTaskDto();
                    endTask.setStep(taskDtos.size() + 1);
                    endTask.setEnd(true);
                    List<LimsSampleProcessStepDto> lastList = taskDtos.get(taskDtos.size() - 1).getList();
                    taskDtos.add(endTask);

                    List<LimsSampleProcessStepDto> list = new ArrayList<>();
                    endTask.setList(list);
                    for (int i = 0; i < lastList.size(); i++) {
                        LimsSampleProcessStepDto endStep = new LimsSampleProcessStepDto();
                        endStep.setEnd(true);
                        list.add(endStep);
                        if (lastList.get(i).getStatus() == 2) {
                            endStep.setStatus(1);
                        } else {
                            endStep.setStatus(lastList.get(i).getStatus());
                        }
                    }
                });
            }
        });
        return req;
    }
}
